package com.eairlv.route.agent.filter;

import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders;
import com.netflix.util.Pair;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author eairlv
 * @description
 * @date 10:01 2019/8/28
 */
@Slf4j
@Component
public class RoutePostFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        // 兼容外部应用进行了API跨域配置
        removeCorsHeader(ctx);
        return null;
    }

    private void removeCorsHeader(RequestContext ctx) {
        List<Pair<String, String>> pairList = Lists.newArrayList();
        ctx.getZuulResponseHeaders().forEach(e -> {
            if (HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN.equals(e.first())
                    || HttpHeaders.ORIGIN.equals(e.second())
                    || HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS.equals(e.second())
                    || HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS.equals(e.second())
                    || HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS.equals(e.first())) {
                pairList.add(e);
            }
        });
        pairList.forEach(e -> ctx.getZuulResponseHeaders().remove(e));
    }
}
